package com.zlj.jdbc.utils.operation;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 没有添加事务，把获取连接和增删改查分离开来的JdbcUtils，传入参数时用了可变参数
 * @author bashen
 *
 */
public class JdbcUtils03 {
	private static Properties properties = null;
	private static Connection conn = null;
	private static PreparedStatement pstm = null;
	private static ResultSet resultSet = null;
	
	private JdbcUtils03() {
		init();
	}

	private void init() {
		try {
			InputStream in = JdbcUtils03.class.getClassLoader().getResourceAsStream("db.properties");
			properties = new Properties();
			properties.load(in);
			Class.forName(properties.getProperty("dirverClassName"));
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
	}

	private static class LazyLoader {
		private static JdbcUtils03 INSTANCE = new JdbcUtils03();
	}

	public static JdbcUtils03 getInstance() {
		return LazyLoader.INSTANCE;
	}

	/*
	 * 获取数据库连接
	 */
	public Connection getConnection() {
		if (conn == null) {
			try {
				conn = DriverManager.getConnection(properties.getProperty("jdbcUrl"), properties.getProperty("username"), properties.getProperty("password"));
				return conn;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} 
		return conn;
	}
	
	/*
	 * 释放数据库连接
	 */
	public void releaseConnection() {
		try {
			if (resultSet != null) {
				resultSet.close();
			}

			if (pstm != null) {
				pstm.close();
			}

			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
